﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace Service
{
    using System.Xml;
    using System.Xml.XPath;

    public class ContactService : IContactService
    {
        readonly string strFileName = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + System.Configuration.ConfigurationManager.AppSettings["path"];

        public void AddContact(Contact contact)
        {
            if (contact != null)
            {
                try
                {
                    var document = new XmlDocument();
                    document.Load(strFileName);

                    XPathNavigator n = document.CreateNavigator().SelectSingleNode("//Contact[@Email='" + contact.Email + "']");
                    if (n == null)
                    {
                        XmlElement element = document.CreateElement("Contact");
                        element.SetAttribute("Name", contact.Name);
                        element.SetAttribute("Email", contact.Email);
                        element.SetAttribute("PhoneNumber", contact.PhoneNumber);
                        document.GetElementsByTagName("Contacts")[0].AppendChild(element);
                        document.Save(strFileName);
                    }
                    else
                    {
                        document.Save(strFileName);
                        throw new FaultException("This email was used!");
                    }
                }
                catch (Exception ex)
                {
                    throw new FaultException(ex.Message);
                }
            }
        }
    }
}
